package com.yuanye.yeecho.utils;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkCapabilities;
import android.net.NetworkRequest;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiNetworkSpecifier;
import android.os.Build;
import android.util.Log;

import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;

import com.yuanye.yeecho.base.BaseActivity;
import com.yuanye.yeecho.callback.CommonCallback;

import java.util.List;

public class WifiUtil {
    private static final String TAG = WifiUtil.class.getName();
    private static WifiUtil sInstance = null;
    private WifiManager mWifiManager;
    private int networkId;
    private Context context;
    private ConnectivityManager connectivityManager;


    public WifiUtil(Context context) {
        this.context = context;
        mWifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        connectivityManager = (ConnectivityManager) context.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
    }

    public static WifiUtil getInstance(Context context) {
        if (sInstance == null) {
            synchronized (WifiUtil.class) {
                if (sInstance == null) {
                    sInstance = new WifiUtil(context);
                }
            }
        }
        return sInstance;
    }

    /**
     * 打开WiFi
     *
     * @return
     */
    public boolean openWifi() {
        boolean opened = true;
        if (!mWifiManager.isWifiEnabled()) {
            opened = mWifiManager.setWifiEnabled(true);
        }
        return opened;
    }

    /**
     * 关闭wifi
     *
     * @return
     */
    public boolean closeWifi() {
        boolean closed = true;
        if (mWifiManager.isWifiEnabled()) {
            closed = mWifiManager.setWifiEnabled(false);
        }
        return closed;
    }

    public WifiManager getWifiManager() {
        return mWifiManager;
    }

    public void checkWifiConnection(final String wifiName, final String password, final CommonCallback callback){
        new Thread(new Runnable() {
            @SuppressLint("NewApi")
            @Override
            public void run() {
                if (mWifiManager.isWifiEnabled()){
                    tryConnectToWifi(wifiName, password, callback);
                }else{
                    callback.info("wifi未打开");
                    callback.info("正在打开..");
                    openWifi();
                    for (int i=0; i<100; i++){
                        try {
                            Thread.sleep(300);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        if (mWifiManager.isWifiEnabled()){
                            callback.info("wifi已打开");
                            tryConnectToWifi(wifiName, password, callback);
                            return;
                        }
                    }
                    callback.onFail("wifi打开失败");
                }
            }
        }).start();

    }

    protected void tryConnectToWifi(String wifiName, String password, CommonCallback callback){
        if (isConnected(wifiName)){
            callback.info("当前已经连接到["+wifiName+"]");
            callback.onSuccess();
        }else{
            callback.info("正在连接["+wifiName+"]..");
            connectToWifi(wifiName, password);
            for (int i=0; i<10; i++){
                try {
                    Thread.sleep(300);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (isConnected(wifiName)){
                    callback.info("已连接到["+wifiName+"]");
                    callback.onSuccess();
                    return;
                }
            }
            callback.onFail("["+wifiName+"]连接超时");
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.Q)
    public void connectToWifi(String SSID, String password, ConnectivityManager.NetworkCallback callback) {
        WifiNetworkSpecifier.Builder builder = new WifiNetworkSpecifier.Builder();
        builder.setSsid(SSID); // SSID为字符串，不包含引号
        builder.setWpa2Passphrase(password); // password为Wi-Fi密码
        WifiNetworkSpecifier wifiNetworkSpecifier = builder.build();

        NetworkRequest.Builder request = new NetworkRequest.Builder();
        request.addTransportType(NetworkCapabilities.TRANSPORT_WIFI);
        request.setNetworkSpecifier(wifiNetworkSpecifier);
        NetworkRequest networkRequest = request.build();

        if (connectivityManager != null) {
            connectivityManager.requestNetwork(networkRequest, callback);
        }
    }


    /**
     * 是否已连接指定wifi
     */
    public boolean isConnected(String ssid) {
        WifiInfo wifiInfo = mWifiManager.getConnectionInfo();

        if (wifiInfo == null) {
            Log.d(TAG, "isConnected: wifiInfo null");
            return false;
        } else {
            Log.d(TAG, "isConnected: [" + wifiInfo.getSSID() + "]");
        }
        switch (wifiInfo.getSupplicantState()) {
            case AUTHENTICATING:
            case ASSOCIATING:
            case ASSOCIATED:
            case FOUR_WAY_HANDSHAKE:
            case GROUP_HANDSHAKE:
            case COMPLETED:
                return wifiInfo.getSSID().replace("\"", "").equals(ssid);
            default:
                return false;
        }
    }

    // 连接到指定的Wifi网络
    public boolean connectToWifi(String ssid, String password) {
        int networkId = findExistingWifiNetworkId(ssid);
        Log.d(TAG, "connectToWifi - networkId: "+networkId);
        if (networkId == -1){
            WifiConfiguration wifiConfig = createWifiConfiguration(ssid, password);
            networkId = mWifiManager.addNetwork(wifiConfig);
            Log.d(TAG, "connectToWifi - networkId2:"+networkId);
        }
        return mWifiManager.enableNetwork(networkId, true);
    }

    // 创建WifiConfiguration对象
    private WifiConfiguration createWifiConfiguration(String ssid, String password) {
        WifiConfiguration wifiConfig = new WifiConfiguration();
        wifiConfig.SSID = "\"" + ssid + "\"";
        wifiConfig.preSharedKey = "\"" + password + "\"";
        wifiConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
        return wifiConfig;
    }

    // 获取当前已连接的Wifi的SSID
    public String getConnectedWifiSSID() {
        WifiInfo wifiInfo = mWifiManager.getConnectionInfo();
        if (wifiInfo != null) {
            return wifiInfo.getSSID();
        }
        return null;
    }

    public int findExistingWifiNetworkId(String ssid) {
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            Log.d(TAG, "没有权限");
            return -1;
        }
        List<WifiConfiguration> configuredNetworks = mWifiManager.getConfiguredNetworks();
        if (configuredNetworks != null) {
            for (WifiConfiguration config : configuredNetworks) {
                if (config.SSID != null && config.SSID.equals("\"" + ssid + "\"")) {
                    return config.networkId;
                }
            }
        }
        return -1;
    }


    public void disconnectAndForgetAllWifi() throws Exception {
        if (mWifiManager == null) {
            return;
        }
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            Log.d(TAG, "没有权限");
            return;
        }
        for (WifiConfiguration config : mWifiManager.getConfiguredNetworks()) {
            Log.d(TAG, "disconnectAndForgetAllWifi: netId "+config.networkId);
            mWifiManager.removeNetwork(config.networkId);
            mWifiManager.saveConfiguration();
        }
    }

}
